package com.uduemc.biso.node.module.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.core.extities.center.Site;
import com.uduemc.biso.core.extities.center.custom.statistics.NodeTemplate;
import com.uduemc.biso.core.extities.center.custom.statistics.NodeTemplateRank;
import com.uduemc.biso.core.extities.center.custom.statistics.NodeTemplateRankRows;
import com.uduemc.biso.node.core.entities.SConfig;
import com.uduemc.biso.node.module.mapper.SConfigMapper;
import com.uduemc.biso.node.module.service.HostService;
import com.uduemc.biso.node.module.service.SConfigService;
import com.uduemc.biso.node.module.service.SiteService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class SConfigServiceImpl implements SConfigService {

	@Autowired
	private SConfigMapper sConfigMapper;

	@Autowired
	private SiteService siteServiceImpl;

	@Autowired
	private HostService hostServiceImpl;

	@Override
	public SConfig insertAndUpdateCreateAt(SConfig sConfig) {
		sConfigMapper.insert(sConfig);
		SConfig findOne = findOne(sConfig.getId());
		Date createAt = sConfig.getCreateAt();
		if (createAt != null) {
			sConfigMapper.updateCreateAt(findOne.getId(), createAt, SConfig.class);
		}
		return findOne;
	}

	@Override
	public SConfig insert(SConfig sConfig) {
		sConfigMapper.insertSelective(sConfig);
		return findOne(sConfig.getId());
	}

	@Override
	public SConfig updateById(SConfig sConfig) {
		sConfigMapper.updateByPrimaryKeySelective(sConfig);
		return findOne(sConfig.getId());
	}

	@Override
	public SConfig updateAllById(SConfig sConfig) {
		sConfigMapper.updateByPrimaryKey(sConfig);
		return findOne(sConfig.getId());
	}

	@Override
	public SConfig findOne(Long id) {
		return sConfigMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<SConfig> findAll(Pageable pageable) {
		int pageNumber = pageable.getPageNumber();
		int pageSize = pageable.getPageSize();
		PageHelper.startPage(pageNumber, pageSize);
		List<SConfig> list = sConfigMapper.selectAll();
		return list;
	}

	@Override
	public void deleteById(Long id) {
		sConfigMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int deleteByHostSiteId(long hostId, long siteId) {
		Example example = new Example(SConfig.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		return sConfigMapper.deleteByExample(example);
	}

	@Override
	public SConfig findInfoByHostSiteId(Long hostId, Long siteId) {
		Example example = new Example(SConfig.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		example.setOrderByClause("`id` ASC");
		List<SConfig> selectByExample = sConfigMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(selectByExample)) {
			return null;
		}
		if (selectByExample.size() > 1) {
			for (int i = 1; i < selectByExample.size(); i++) {
				SConfig sConfig = selectByExample.get(i);
				deleteById(sConfig.getId());
			}
		}
		return selectByExample.get(0);
	}

	@Override
	public void init(Long hostId, Long siteId) {
		SConfig sConfig = findInfoByHostSiteId(hostId, siteId);
		if (sConfig != null && sConfig.getId() > 0) {
			return;
		}
		sConfig = new SConfig();
		sConfig.setHostId(hostId).setSiteId(siteId).setIsMain((short) 0).setColor("0").setTheme("1").setMenuConfig("").setCustomThemeColorConfig("");

		insert(sConfig);
	}

	@Override
	public SConfig findDefaultSConfigByHostId(Long hostId) {
		Example example = new Example(SConfig.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("status", 1);
		example.setOrderByClause("`is_main` DESC, `order_num` ASC, `id` ASC");
		List<SConfig> selectByExample = sConfigMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(selectByExample)) {
			selectByExample = findByHostId(hostId);
		}
		if (CollectionUtils.isEmpty(selectByExample)) {
			return null;
		}
		for (SConfig sConfig : selectByExample) {
			Site site = siteServiceImpl.findOne(sConfig.getSiteId());
			if (site != null && site.getStatus().shortValue() == 1) {
				return sConfig;
			}
		}
		return null;
	}

	@Override
	public void updateSiteBanner(long hostId, long siteId, short siteBanner) {
		SConfig findInfoByHostSiteId = findInfoByHostSiteId(hostId, siteId);
		if (findInfoByHostSiteId != null) {
			findInfoByHostSiteId.setSiteBanner(siteBanner);
			updateAllById(findInfoByHostSiteId);
		}
	}

	@Override
	public List<SConfig> findOkInfoByHostId(long hostId) {
		Example example = new Example(SConfig.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("status", 1);
		example.setOrderByClause("`is_main` DESC, `order_num` ASC, `id` ASC");
		List<SConfig> selectByExample = sConfigMapper.selectByExample(example);
		return selectByExample;
	}

	@Override
	public List<SConfig> findByHostId(long hostId) {
		Example example = new Example(SConfig.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		example.setOrderByClause("`is_main` DESC, `order_num` ASC, `id` ASC");
		List<SConfig> selectByExample = sConfigMapper.selectByExample(example);
		return selectByExample;
	}

	@Override
	public List<SConfig> findOKByHostId(long hostId) {
		List<SConfig> data = sConfigMapper.findOKByHostId(hostId, "`s_config`.`order_num` ASC, `s_config`.`id` ASC");
		return data;
	}

	@Transactional
	@Override
	public boolean changeMainSiteByHostId(long hostId, long mainSiteId) {
		List<SConfig> findByHostId = findByHostId(hostId);
		if (CollectionUtils.isEmpty(findByHostId)) {
			return false;
		}
		boolean exists = false;
		Iterator<SConfig> iterator = findByHostId.iterator();
		while (iterator.hasNext()) {
			SConfig sConfig = iterator.next();
			if (sConfig.getIsMain().shortValue() == (short) 1) {
				// 更新下
				sConfig.setIsMain((short) 0);
				updateAllById(sConfig);
			}
			if (sConfig.getSiteId().longValue() == mainSiteId) {
				sConfig.setIsMain((short) 1);
				updateAllById(sConfig);
				exists = true;
			}
		}
		if (exists == false) {
			throw new RuntimeException("未能找到需要修改默认站点的数据！ mainSiteId：" + mainSiteId);
		}
		return true;
	}

	@Override
	public PageInfo<SConfig> findPageInfoAll(long hostId, long siteId, int pageNum, int pageSize) {
		Example example = new Example(SConfig.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		PageHelper.startPage(pageNum, pageSize);
		List<SConfig> listSConfig = sConfigMapper.selectByExample(example);
		PageInfo<SConfig> result = new PageInfo<>(listSConfig);
		return result;
	}

	@Override
	public void updateMenuFootfixedConfig(long hostId, long siteId, String menuFootfixedConfig) {
		if (StrUtil.isBlank(menuFootfixedConfig)) {
			return;
		}
		SConfig sConfig = findInfoByHostSiteId(hostId, siteId);
		sConfig.setMenuFootfixedConfig(StrUtil.isBlank(menuFootfixedConfig) ? "" : menuFootfixedConfig);
		updateAllById(sConfig);
	}

	@Override
	public NodeTemplateRank queryTemplateRank(int trial, int review, int templateAll, int orderBy, int count) {
		String orderByString = "DESC";
		if (orderBy == 0) {
			orderByString = "ASC";
		}
		List<NodeTemplateRankRows> rows = sConfigMapper.queryTemplateRank(trial, review, templateAll, orderByString, count);

		Integer hostTotal = hostServiceImpl.queryAllCount(trial, review);
		Integer siteTotal = siteServiceImpl.queryAllCount(trial, review);
		NodeTemplateRank result = NodeTemplateRank.makeNodeTemplateRank(hostTotal, siteTotal, rows);
		return result;
	}

	@Override
	public NodeTemplateRank queryTemplateByTrialReviewTemplateIds(int trial, int review, String templateIdsString) {
		Integer hostTotal = hostServiceImpl.queryAllCount(trial, review);
		Integer siteTotal = siteServiceImpl.queryAllCount(trial, review);

		List<String> templateIds = StrUtil.split(templateIdsString, ",");
		if (CollUtil.isEmpty(templateIds)) {
			return null;
		}
		List<NodeTemplateRankRows> rows = new ArrayList<>(templateIds.size());
		for (String templateIdString : templateIds) {
			if (!NumberUtil.isNumber(templateIdString)) {
				return null;
			}
			Long templateId = Long.valueOf(templateIdString);
			Integer count = sConfigMapper.queryTemplate(trial, review, templateId);

			rows.add(new NodeTemplateRankRows(templateId, count));
		}
		return NodeTemplateRank.makeNodeTemplateRank(hostTotal, siteTotal, rows);
	}

	@Override
	public NodeTemplate queryTemplate(int trial, int review, long templateId) {
		NodeTemplate nodeTemplate = new NodeTemplate();
		Integer count = sConfigMapper.queryTemplate(trial, review, templateId);
		Integer hostTotal = hostServiceImpl.queryAllCount(trial, review);
		Integer siteTotal = siteServiceImpl.queryAllCount(trial, review);

		nodeTemplate.setTemplateId(templateId).setHostTotal(hostTotal).setSiteTotal(siteTotal).setCount(count);

		return nodeTemplate;
	}

	@Override
	public Integer queryFootMenuCount(int trial, int review) {
		return sConfigMapper.queryFootMenuCount(trial, review);
	}
}
